package com.youlai.boot.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.mybatisflex.core.query.QueryMethods;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.youlai.boot.common.constant.RedisConstants;
import com.youlai.boot.common.constant.SecurityConstants;
import com.youlai.boot.system.enums.MenuTypeEnum;
import com.youlai.boot.system.mapper.RoleMapper;
import com.youlai.boot.system.mapper.RoleMenuMapper;
import com.youlai.boot.system.model.bo.RolePermsBO;
import com.youlai.boot.system.model.entity.SysMenuEntity;
import com.youlai.boot.system.model.entity.SysRoleEntity;
import com.youlai.boot.system.model.entity.SysRoleMenuEntity;
import com.youlai.boot.system.service.RoleMenuService;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 角色菜单业务实现
 *
 * @author Ray.Hao
 * @since 2.5.0
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, SysRoleMenuEntity> implements RoleMenuService {

    private final RoleMapper roleMapper;
    private final RedisTemplate<String, Object> redisTemplate;

    /**
     * 初始化权限缓存
     */
    @PostConstruct
    public void initRolePermsCache() {
        log.info("初始化权限缓存... ");
        refreshRolePermsCache();
    }

    /**
     * 刷新权限缓存
     */
    @Override
    public void refreshRolePermsCache() {
        // 清理权限缓存
        redisTemplate.opsForHash().delete(RedisConstants.System.ROLE_PERMS, "*");

        List<RolePermsBO> list = this.getRolePermsList(null);
        if (CollectionUtil.isNotEmpty(list)) {
            list.forEach(item -> {
                String roleCode = item.getRoleCode();
                Set<String> perms = item.getPerms();
                if (CollectionUtil.isNotEmpty(perms)) {
                    redisTemplate.opsForHash().put(RedisConstants.System.ROLE_PERMS, roleCode, perms);
                }
            });
        }
    }

    /**
     * 获取权限和拥有权限的角色列表
     */
    @Override
    public List<RolePermsBO> getRolePermsList(String roleCode) {
        return roleMapper.selectListWithRelationsByQueryAs(
                QueryWrapper.create().from(SysRoleEntity.class)
                        .select(
                                QueryMethods.column(SysRoleEntity::getCode).as(RolePermsBO::getRoleCode),
                                QueryMethods.column(SysRoleEntity::getId).as(RolePermsBO::getId)
                        )
                        .innerJoin(SysRoleMenuEntity.class).on(on->on.and(SysRoleMenuEntity::getRoleId).eq(SysRoleEntity::getId))
                        .and(SysRoleEntity::getCode).eq(roleCode, StrUtil.isNotBlank(roleCode))
                        .and(SysRoleEntity::getStatus).eq(1),
                RolePermsBO.class
        );
    }

    /**
     * 刷新权限缓存
     */
    @Override
    public void refreshRolePermsCache(String roleCode) {
        // 清理权限缓存
        redisTemplate.opsForHash().delete(RedisConstants.System.ROLE_PERMS, roleCode);

        List<RolePermsBO> list = this.getRolePermsList(roleCode);
        if (CollectionUtil.isNotEmpty(list)) {
            RolePermsBO rolePerms = list.get(0);
            if (rolePerms == null) {
                return;
            }

            Set<String> perms = rolePerms.getPerms();
            if (CollectionUtil.isNotEmpty(perms)) {
                redisTemplate.opsForHash().put(RedisConstants.System.ROLE_PERMS, roleCode, perms);
            }
        }
    }

    /**
     * 刷新权限缓存 (角色编码变更时调用)
     */
    @Override
    public void refreshRolePermsCache(String oldRoleCode, String newRoleCode) {
        // 清理旧角色权限缓存
        redisTemplate.opsForHash().delete(RedisConstants.System.ROLE_PERMS, oldRoleCode);

        // 添加新角色权限缓存
        List<RolePermsBO> list = this.getRolePermsList(newRoleCode);
        if (CollectionUtil.isNotEmpty(list)) {
            RolePermsBO rolePerms = list.get(0);
            if (rolePerms == null) {
                return;
            }

            Set<String> perms = rolePerms.getPerms();
            redisTemplate.opsForHash().put(RedisConstants.System.ROLE_PERMS, newRoleCode, perms);
        }
    }

    /**
     * 获取角色权限集合
     *
     * @param roles 角色编码集合
     * @return 权限集合
     */
    @Override
    public Set<String> getRolePermsByRoleCodes(Set<String> roles) {
        return new HashSet<>(this.listAs(
                QueryWrapper.create().from(SysRoleMenuEntity.class)
                        .select(QueryMethods.distinct(SysMenuEntity::getPerm))
                        .innerJoin(SysMenuEntity.class).on(q -> q.and(SysMenuEntity::getId).eq(SysRoleMenuEntity::getMenuId))
                        .innerJoin(SysRoleEntity.class).on(q -> q.and(SysRoleEntity::getId).eq(SysRoleMenuEntity::getRoleId))
                        .and(SysMenuEntity::getType).eq(MenuTypeEnum.BUTTON)
                        .and(SysMenuEntity::getPerm).isNotNull()
                        .and(SysRoleEntity::getCode).in(roles),
                String.class
        ));
    }

    /**
     * 获取角色拥有的菜单ID集合
     *
     * @param roleId 角色ID
     * @return 菜单ID集合
     */
    @Override
    public List<Long> listMenuIdsByRoleId(Long roleId) {
        return this.listAs(
                QueryWrapper.create().from(SysRoleMenuEntity.class)
                        .select(QueryMethods.column(SysRoleMenuEntity::getMenuId))
                        .leftJoin(SysMenuEntity.class).on(q -> q.and(SysMenuEntity::getId).eq(SysRoleMenuEntity::getMenuId))
                        .where(SysRoleMenuEntity::getRoleId).eq(roleId),
                Long.class
        );
    }

}
